<template>
  <div class="affix-container">
    <zh-header-toolbar>
      <zh-button buttonType="add" @click="childDaterCenterAdd">子级新增</zh-button>
      <zh-button buttonType="save" @click="saveForm">保存</zh-button>
      <zh-button buttonType="del" @click="delMeta">删除</zh-button>
      <zh-button buttonType="save" @click="createTable">创建表</zh-button>
      <zh-button buttonType="save" @click="showCreateVO">创建VO</zh-button>
      <zh-button buttonType="save" @click="showCreatePage">创建页面</zh-button>
      <zh-button buttonType="save" @click="showCreateTableMeta">创建元数据</zh-button>
    </zh-header-toolbar>
    <zh-row>
      <zh-col :span="6">
        <zh-card shadow="hover">
          <div>
            <zh-tree
                ref="appmenuTreeRef"
                funcCode="coTableMeta0008"
                moveFuncCode="coTableMeta0012"
                :expand-on-click-node="false"
                :lazy="true"
                node-key="key"
                :height="isTagsview ? `calc(100vh - 142px)` : `calc(100vh - 108px)`"
                :draggable="true"
                :props="{ label: 'title' }"
                @node-click="onNodeClick"
            ></zh-tree>
          </div>
        </zh-card>
      </zh-col>
      <zh-col :span="18">
        <zh-card shadow="hover">
          <el-tabs v-model="activeName" @tab-click="handleClick" :stretch="true">
            <el-tab-pane label="字段信息" name="baseInfo">
              <DataCenterForm ref="CoTableFieldMetaFormRef" :cotablemetaInfo="cotablemetaInfo"/>
            </el-tab-pane>
            <el-tab-pane label="表信息" name="tableList">
              <CoTableMetaForm ref="CoTableMetaFormRef" :cotablemetaInfo="cotablemetaInfo"/>
            </el-tab-pane>
          </el-tabs>
        </zh-card>
      </zh-col>
    </zh-row>
    <el-dialog title="基本属性" v-model="state.showVODialog">
      <zh-form :model="state.basicVOInfo">
        <zh-form-input label="表名" v-model="state.basicVOInfo.tableName"></zh-form-input>
        <zh-form-input label="功能编号" v-model="state.basicVOInfo.funcCode"></zh-form-input>
        <zh-form-input label="主体" v-model="state.basicVOInfo.subject"></zh-form-input>
        <zh-form-input label="作者" v-model="state.basicVOInfo.author"></zh-form-input>
        <zh-form-input label="模块名" v-model="state.basicVOInfo.moduleName"></zh-form-input>
      </zh-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="state.showVODialog = false" size="default">取消</el-button>
					<el-button type="primary" @click="createVO" size="default">确定</el-button>
				</span>
      </template>
    </el-dialog>
    <el-dialog title="页面属性" v-model="state.showCreatePageDialog">
      <zh-form :model="state.createPageVO">
        <zh-form-input label="输出路径" v-model="state.createPageVO.outPath"></zh-form-input>
        <zh-form-input label="表格编号" v-model="state.createPageVO.tableId"></zh-form-input>
        <zh-form-input label="VO名称" v-model="state.createPageVO.VOName"></zh-form-input>
<!--        <zh-form-input label="功能编号" v-model="state.createPageVO.funcCode"></zh-form-input>-->
        <zh-form-input label="主体" v-model="state.createPageVO.subject"></zh-form-input>
        <zh-form-input label="主键" v-model="state.createPageVO.entityId"></zh-form-input>
      </zh-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="state.showCreatePageDialog = false" size="default">取消</el-button>
					<el-button type="primary" @click="createPage" size="default">确定</el-button>
				</span>
      </template>
    </el-dialog>
    <el-dialog title="创建表格元数据" v-model="state.showCreateTableMetaDialog">
      <zh-form :model="state.createTableMetaVO">
        <zh-form-input label="数据源名称" v-model="state.createTableMetaVO.datasourceName" :disabled="true"></zh-form-input>
        <zh-form-input label="表格名称" v-model="state.createTableMetaVO.tableName"></zh-form-input>
      </zh-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="state.showCreateTableMetaDialog = false" size="default">取消</el-button>
					<el-button type="primary" @click="createTableMeta" size="default">确定</el-button>
				</span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup name="dataCenterManager">
import type {TabsPaneContext} from 'element-plus';
import DataCenterForm from '@/views/dataCenter/component/DataCenterForm.vue';
import CoTableMetaForm from '@/views/dataCenter/component/CoTableMetaForm.vue';
import {ElMessage} from 'element-plus';
import ZhFormInput from "@/components/zh-form-input/index.vue";
//----------------定义子组件 begin------------------------------
const CoTableFieldMetaFormRef = ref();
const appmenuTreeRef = ref();
const CoTableMetaFormRef = ref();
const activeName = ref('baseInfo');
//-----------------获取缓存参数-----------------------------
const {isTagsview} = storeToRefs($store.theme);
//---------------------内部变量定义 begin--------------------------------------
const selectNode: any = ref(null);
const cotablemetaInfo = ref({id: '', nodeType: '', tableId: null, columnName: '', datasourceId: '', projectId: ''});
const saveType = ref('edit');
const state = reactive({
  showVODialog: false,
  basicVOInfo: {
    tableName: '',
    funcCode: '',
    subject: '',
    author: '',
    moduleName: '',
  },
  showCreatePageDialog: false,
  createPageVO: {
    outPath: 'D:\\git\\jw-vue-3.0-develop\\src\\views\\dataCenter\\',
    tableId: '',
    VOName: '',
    funcCode: '',
    subject: '',
    entityId: '',
  },
  showCreateTableMetaDialog: false,
  createTableMetaVO: {
    dataSourceid: '',
    datasourceName: '',
    tableName: ''
  }
});
//---------------------内部变量定义 end--------------------------------------

//---------------------定义调用方法--------------------------------------
const handleClick = () => {
  if (!selectNode.value) {
    ElMessage({
      message: '请先在左边路由树中选择需要操作的节点',
      type: 'warning',
    });
    return;
  }
};
const onNodeClick = (node) => {
  console.log('node', node)
  //点击树节点触发事件
  selectNode.value = node;
  cotablemetaInfo.value.id = node.key;
  cotablemetaInfo.value.nodeType = node.nodeType;
  if (selectNode.value.nodeType == '0') {
    cotablemetaInfo.value.datasourceId = node.parentKey;
  }
  else if (selectNode.value.nodeType == '1') {
    console.log('字段node.parentKey', node.parentKey, appmenuTreeRef.value.getNode(node.parentKey))
    cotablemetaInfo.value.datasourceId = appmenuTreeRef.value.getNode(node.parentKey).data.parentKey;
  }

  //console.log("cotablemetaInfo.value.id",node.nodeType)
  saveType.value = 'edit';
  changeActiveName(node.nodeType);
};
//改变tab调用方法
const changeActiveName = (nodeType) => {
  if (nodeType == '0') {
    activeName.value = 'tableList'
  } else if (nodeType == '1') {
    activeName.value = 'baseInfo'
  }
};
const saveForm = async () => {
  console.log('cotablemetaInfo.value.nodeType', cotablemetaInfo.value.nodeType);
  if ((selectNode.value.nodeType == '0' && saveType.value == 'childAdd')
      || (selectNode.value.nodeType == '1' && saveType.value == 'edit')) {
    return saveField();
  } else if ((selectNode.value.nodeType == '3' && saveType.value == 'childAdd')
      || (selectNode.value.nodeType == '0' && saveType.value == 'edit')) {
    return saveTable();
  }
};
const saveField = async () => {
  //保存字段
  let res = await CoTableFieldMetaFormRef.value.saveForm();
  console.log('saveField res', res);
  if (res && res.code === 0) {
    let result = res.result;
    //保存成功
    if (res.saveType === 'add') {
      //新增树节点
      let isLeaf = true;
      let parentKey = '';
      if (result.nodeType === '0') {
        isLeaf = false;
        parentKey = result.datasourceId;
      } else {
        isLeaf = true;
        parentKey = result.tableId;
      }
      const addNode = {
        key: result.id,
        title: result.columnName,
        icon: '',
        nodeType: result.nodeType,
        isLeaf: isLeaf,
        parentKey: parentKey,
      };
      if (saveType.value === 'childAdd') {
        //子集新增
        appmenuTreeRef.value.append(addNode, selectNode.value.key);
      } else {
        //同级新增
        appmenuTreeRef.value.insertBefore(addNode, selectNode.value.key);
      }
      ElMessage.success('新增成功！');
    } else if (res.saveType === 'edit') {
      //更新树节点信息
      selectNode.value.title = result.columnName;
      selectNode.value.icon = result.icon;
      selectNode.value.nodeType = result.nodeType;


      ElMessage.success('修改成功！');
    }
  }
};
const saveTable = async () => {
  //保存字段
  let res = await CoTableMetaFormRef.value.saveForm();
  if (res && res.code === 0) {
    let result = res.result;
    //保存成功
    if (res.saveType === 'add') {
      //新增树节点
      let isLeaf = true;
      if (result.nodeType === '0') {
        isLeaf = false;
      } else {
        isLeaf = true;
      }
      const addNode = {
        key: result.id,
        title: result.tableName,
        icon: '',
        nodeType: result.nodeType,
        isLeaf: isLeaf,
        parentKey: result.datasourceId,
      };
      if (saveType.value === 'childAdd') {
        //子集新增
        appmenuTreeRef.value.append(addNode, selectNode.value.key);
      } else {
        //同级新增
        appmenuTreeRef.value.insertBefore(addNode, selectNode.value.key);
      }
      ElMessage.success('新增成功！');
    } else if (res.saveType === 'edit') {
      //更新树节点信息
      selectNode.value.title = result.columnName;
      selectNode.value.icon = result.icon;
      selectNode.value.nodeType = result.nodeType;

      ElMessage.success('修改成功！');
    }
  }
};
const childDaterCenterAdd = () => {
  //子级新增
  if (selectNode.value) {
    if (selectNode.value.nodeType === '1') {
      $messageBox.warning('字段不能添加子节点', '提示');
      return;
    }
    saveType.value = 'childAdd';
    console.log('childAdd', selectNode.value.nodeType)
    // 父节点
    if (selectNode.value.nodeType == '3') {
      changeActiveName('0');
      cotablemetaInfo.value = {
        id: '',
        projectId: '',
        datasourceId: selectNode.value.key,
        tableSchema: '',
        tableName: '',
        tableFullName: '',
        tableType: '',
        tableComment: '',
        topicId: '',
        boxLevel: '',
        safeLevel: '',
        productFrequency: '',
        etlTime: '',
        etlMode: '',
        valid: '',
        uniformity: '',
      };
      state.propertyMeta
    } else if (selectNode.value.nodeType == '0') {
      changeActiveName('1');
      let oldDaterCenter = CoTableMetaFormRef.value.selectTable;
      cotablemetaInfo.value = {
        tableId: oldDaterCenter.id,
        datasourceId: selectNode.value.parentKey,
        id: '',
        columnName: '',
        columnComment: '',
        columnDesc: '',
        dataType: null,
        dataLength: '',
        dataScale: '',
        primarykey: null,
        nullable: null,
        safelevel: null,
        desensitization: null
      };
    }
  } else {
    ElMessage({
      message: '请先在左边路由树中选择节点',
      type: 'warning',
    });
  }
};

const createTable = () => {
  if (selectNode.value.nodeType == "0") {
    const params = {tableId: selectNode.value.key}
    $api.common.send.post('coTableFieldMeta0007', params)
        .then(() => {
          $messageBox.success('创建表成功', '成功提示');
        })
        .catch(() => {
        });
  } else {
    ElMessage.success('该节点不是表字段无法创建表！');
  }
}

const showCreateVO = () => {
  state.showVODialog = true;
  state.basicVOInfo.tableName = CoTableMetaFormRef.value.tableCenter.tableName;
}

const createVO = () => {
  if (selectNode.value.nodeType == "0") {
    $api.common.send.post('generate0001', {...state.basicVOInfo}).then((res) => {
      if (res.code == 0) {
        $messageBox.alert('创建VO成功');
      }
    });
  } else {
    ElMessage.success('该节点不是表字段无法创建VO！');
  }
}

const showCreatePage = () => {
  state.showCreatePageDialog = true;
  state.createPageVO.tableId = CoTableMetaFormRef.value.tableCenter.id;
}

const createPage = () => {
  if (selectNode.value.nodeType == "0") {
    $api.common.send.post('generate0002', {...state.createPageVO}).then((res) => {
      if (res.code == 0) {
        $messageBox.alert('创建页面成功');
      }
    });
  } else {
    ElMessage.success('该节点不是表字段无法创建页面！');
  }
}

const delMeta = () => {
  let message = '';
  let funcCode = '';
  let params = {};
  if (selectNode.value.nodeType == '0') {
    message = '确定删除该表？删除表会同时删除表中的字段';
    funcCode = 'coTableMeta0006';
    params.id = selectNode.value.key;
  } else if (selectNode.value.nodeType == '1') {
    message = '确定删除该字段？';
    funcCode = 'coTableFieldMeta0006';
    params.id = selectNode.value.key;
  } else {
    $messageBox.alert('只能删除表节点和字段节点');
    return;
  }
  $messageBox.confirm(message, '提示').then(() => {
    $api.common.send.post(funcCode, params).then((res) => {
      if (res.code == 0) {
        $messageBox.alert('删除成功');
        //删除
        appmenuTreeRef.value.remove(selectNode.value.key);
      }
    });
  });
}

const showCreateTableMeta = () => {
  if (!selectNode || selectNode.value.nodeType != '3') {
    $messageBox.warning('该节点不是数据源，无法创建元数据！')
    return;
  }
  state.showCreateTableMetaDialog = true;
  state.createTableMetaVO.dataSourceid = selectNode.value.key;
  state.createTableMetaVO.datasourceName = selectNode.value.title;
}

const createTableMeta = () => {
  $api.common.send.post('generate0003', state.createTableMetaVO).then(res => {
    if (res.code == 0) {
      $messageBox.alert('创建表元数据成功');
    }
  });
}

// 页面加载时
</script>
<style lang="scss" scoped></style>
